package logic

import (
	"errors"
	"myself/db/managers"
	"myself/db/models"
)

type PostingLogic struct {
	tableName string
}

func NewPostingLogic() *PostingLogic {
	return &PostingLogic{tableName: "account"}
}

func (PostingLogic) CreatePosting(title string, content string, accountId string) (*models.Posting, error) {
	posting := &models.Posting{Title: title, Content: content, AccountId: accountId}
	postingManger, err := managers.NewPostingManager()
	if err != nil {
		return nil, err
	}
	modelInfo, err := postingManger.Create(posting)
	return modelInfo.(*models.Posting), err
}

func checkOwn(id uint32, accountId string) bool {
	postingManager, err := managers.NewPostingManager()
	if err != nil {
		return false
	}
	count, err := postingManager.GetCount(managers.Condition{
		FilterMap: map[string]interface{}{
			"id":         id,
			"account_id": accountId,
		},
	})
	if count > 0 {
		return true
	}
	return false
}

func (PostingLogic) UpdatePosting(id uint32, title *string, content *string, accountId string) (int64, error) {
	if !checkOwn(id, accountId) {
		return 0, errors.New("非本人所属帖子")
	}
	updateInfo := make(map[string]interface{})
	if title != nil {
		updateInfo["title"] = *title
	}
	if content != nil {
		updateInfo["content"] = *content
	}
	postingManger, err := managers.NewPostingManager()
	if err != nil {
		return 0, err
	}
	return postingManger.UpdateById(id, updateInfo)
}

// SelectAllPosting 如果有id，则查id，否则模糊查询
func (p PostingLogic) SelectAllPosting(id *uint32, title *string, content *string, ownerId *string) ([]models.Posting, error) {
	postingManger, err := managers.NewPostingManager()
	modelInfoList := make([]models.Posting, 0)
	if err != nil {
		return modelInfoList, err
	}
	if id != nil {
		postingManger.Conn.Model(postingManger.GetNewModel()).Where("id = ?", *id).Scan(&modelInfoList)
		if err != nil {
			return modelInfoList, err
		}
		return modelInfoList, nil
	}
	var t string
	if title != nil {
		t = "%" + *title + "%"
	} else {
		t = "%"
	}
	var c string
	if content != nil {
		c = "%" + *content + "%"
	} else {
		c = "%"
	}
	var a string
	if ownerId != nil {
		a = *ownerId
	} else {
		a = "%"
	}

	postingManger.Conn.Model(postingManger.GetNewModel()).Where("title like ? and content like ? and account_id like ?", t, c, a).Scan(&modelInfoList)
	if err != nil {
		return modelInfoList, err
	}
	return modelInfoList, nil
}
